<template>
  <div class="review">
    <!-- 发表攻略 -->
    <div class="publish">
      <h2>发表新攻略</h2>
      <p>分享你的个人游记,让更多人看到哟</p>
      <el-form>
        <el-form-item>
          <el-input
            placeholder="请输入标题"
            v-model="headline"
            class="ipt"
          ></el-input>
          <!-- 必须使用client-only否则会报错 富文本框 -->
          <client-only class="edi">
            <!-- <vue-editor v-model="contents"></vue-editor> -->
            <vue-editor
              id="editor"
              useCustomImageHandler
              @image-added="handleImageAdded"
              v-model="htmlForEditor"
            >
            </vue-editor>
          </client-only>
        </el-form-item>
        <!-- 选择城市 -->
        <div class="city">
          <span class="citys">选择城市</span>
          <el-autocomplete
            :fetch-suggestions="queryDepartSearch"
            placeholder="请搜索游玩城市"
            :trigger-on-focus="false"
            :highlight-first-item="true"
            @select="handleDepartSelect"
            class="int"
            v-model="form.city"
          ></el-autocomplete>
        </div>
      </el-form>
      <div class="issue">
        <el-button type="primary" @click="fabu">发布</el-button>
        <span class="as"
          >或者
          <a href="#" @click="issue">保存到草稿</a>
        </span>
      </div>
    </div>
    <!-- 草稿箱 -->
    <div class="draft">
      <h4>
        草稿箱({{ $store.state.review.savedraft.length }})
        <div
          v-for="(value, index) in $store.state.review.savedraft"
          :key="index"
        >
          {{ value.title }}
          <!-- <div v-html="value.content"></div>
          {{ value.city }} -->
          <div class="s">
            <p>{{ moment(value.date).format("YYYY-MM-DD") }}</p>
            <span class="el-icon-edit" @click="compile(value)"></span>
            <span class="el-icon-delete" @click="cancel"></span>
          </div>
        </div>
      </h4>
    </div>
  </div>
</template>
<script>
// 使用插件的方式来添加富文本框因此不需要再引入
// import { VueEditor } from "vue2-editor";
import moment from "moment";
export default {
  data() {
    return {
      form: {
        city: "", //搜索游玩城市
      },
      headline: "",
      contents: "",
      htmlForEditor: "",
      moment,
    };
  },
  methods: {
    // 图片上传
    handleImageAdded: function (file, Editor, cursorLocation, resetUploader) {
      var formData = new FormData();
      formData.append("files", file);

      this.$axios({
        url: "/upload",
        method: "post",
        data: formData,
      })
        .then((result) => {
          console.log(result);
          let url = this.$axios.defaults.baseURL + result.data[0].url; // Get url from response
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 编辑草稿
    compile(value) {
      console.log(value);
      this.contents = value.content;
      this.headline = value.title;
      this.form.departCity = value.city;
    },
    // 删除草稿
    cancel() {
      this.$store.commit("review/delete");
      console.log("删除成功");
    },
    // 添加到草稿
    issue() {
      this.$store.commit("review/issue", {
        title: this.headline,
        content: this.contents,
        city: this.form.departCity,
        date: new Date(),
      });
    },
    // 搜索游玩城市
    queryDepartSearch(value, cb) {
      // JiPiao - 实时机票城市：http:127.0.0.1:1337/airs/city
      // 目标城市输入框获得焦点时触发
      // value 是选中的值，cb是回调函数，接收要展示的列表
      this.getSuggestions(value, "depart", cb);
    },
    getSuggestions(value, type, cb) {
      this.$axios({
        url: "/airs/city",
        params: { name: value },
      }).then((res) => {
        console.log(res);
        let list;
        if (res.data.data.length == 0) {
          cb([{ value: "没有查询到相应的城市" }]);
          return;
        }
        // 改造的查询数据匹配组件的需要
        list = res.data.data.map((v) => {
          // 这里为什么要做改造，因为autocomplete组件规定，只有对象中的Value属性才会显示
          return {
            value: v.name,
            code: v.sort,
          };
        });
        // 过滤掉没有Code的城市，因为它不可能会购票成功
        list = list.filter((v) => {
          return v.code; // 不为null则需要
        });
        console.log(list);
        if (type == "depart") {
          this.form.departCity = list[0].value;
          this.form.departCode = list[0].code;
        } else {
          this.form.destCity = list[0].value;
          this.form.destCode = list[0].code;
        }
        cb(list);
      });
    },

    handleDepartSelect(item) {
      console.log(item);
      // 拿到后台返回的value
      this.form.departCity = item.value;
      this.form.departCode = item.code;
    },
    // 发布
    fabu() {
      // console.log("发布成功");
      this.$axios({
        url: "/posts",
        method: "post",
        // 由于发送请求之后需要登录,这里需要token来判断是否登录过
        headers: {
          Authorization: "Bearer " + this.$store.state.user.userinfo.token,
        },
        data: {
          title: this.headline,
          content: this.contents,
          city: this.form.departCity,
        },
      }).then((res) => {
        console.log(res);
        if (res.data.message === "新增成功") {
          (this.headline = ""), (this.contents = "");
          this.form.departCity = "";
          this.htmlForEditor = "";
        }
      });
      if (this.form.city === "") {
        this.$message({
          message: "城市不能为空",
          type: "error",
        });
      } else {
        this.$message({
          message: "发布成功",
          type: "success",
        });
      }
    },
  },
  components: {},
};
</script>

<style lang="less" scoped>
.review {
  width: 1000px;
  margin: 0 auto;
  padding: 20px 0;
  font-size: 16px;
  display: flex;
  .publish {
    flex: 8;
    margin-right: 20px;
    h2 {
      font-weight: 400;
      font-size: 22px;
      margin-bottom: 10px;
    }
    p {
      font-size: 12px;
      color: #999;
      margin-bottom: 10px;
    }
    .ipt {
      margin-bottom: 20px;
    }
    .int {
      width: 200px;
      margin: 0 10px;
    }
    .city {
      margin-bottom: 20px;
      .citys {
        font-size: 15px;
      }
    }
    .issue {
      .as {
        margin-left: 20px;
      }
      a {
        color: #ffa500;
        font-size: 12px;
      }
    }
    /deep/ .ql-toolbar .ql-snow {
      background-color: red;
    }
  }
  .draft {
    flex: 2;
    h4 {
      border: 1px solid #ddd;
      padding: 10px;
      font-weight: 400;
      color: #666;
      .s {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
      }
    }
  }
}
</style>